package com.hpp.web.api;

import java.util.HashMap;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.hpp.model.NewsInfo;
import com.hpp.model.NewsType;
import com.hpp.service.INewsService;
import com.hpp.utils.ConfigUtil;
import com.hpp.utils.RespJson;
import com.hpp.utils.ResultCode;
import com.hpp.web.NewsController;

@Controller
@RequestMapping(value = "/api")
public class ApiController {
	
	private Logger logger = LoggerFactory.getLogger(NewsController.class);
	
	@Autowired
	INewsService newsService;
	
	/**
	 * @param newsTypeId
	 * @return获取新闻列表
	 */
	@ResponseBody
	@RequestMapping(value = "/news/list")
	public RespJson getNewsList(
			@RequestParam(value = "newsTypeId",required = true) Integer newsTypeId){
		try {
			HashMap<String, Object> map = new HashMap<String,Object>();
			map.put("newsTypeId", newsTypeId);
			List<NewsInfo> list = newsService.getNewsInfoList(map);
			return new RespJson(true, "获取成功", ResultCode.SUCCESS, list);
		} catch (Exception e) {
			logger.error("获取异常：" + e);
			return new RespJson(false, "获取失败", ResultCode.ERROR, "");
		}
	}
	
	/**
	 * @param id
	 * @return 获取新闻详情
	 */
	@ResponseBody
	@RequestMapping(value = "/news/info")
	public RespJson getNewsInfo(
			@RequestParam(value = "id",required = true) Integer id,
			@RequestParam(value = "newsTypeId",required = true) Integer newsTypeId){
		try {
			HashMap<String, Object> result = new HashMap<String,Object>();
			HashMap<String, Object> map = new HashMap<String,Object>();
			map.put("id", id);
			map.put("newsTypeId", newsTypeId);
			NewsInfo info = newsService.getNewsInfo(map);
			if (info != null) {
				map.clear();
				map.put("newsTypeId", newsTypeId);
				map.put("beforeTime", info.getCreateTime());
				NewsInfo before = newsService.getNewsInfo(map);
				map.clear();
				map.put("newsTypeId", newsTypeId);
				map.put("afterTime", info.getCreateTime());
				NewsInfo after = newsService.getNewsInfo(map);
				info.setPath(ConfigUtil.get("url") + info.getImgPath());
				result.put("before", before);
				result.put("after", after);
				result.put("info", info);
			}
			return new RespJson(true, "获取成功", ResultCode.SUCCESS, result);
		} catch (Exception e) {
			logger.error("获取异常：" + e);
			return new RespJson(false, "获取失败", ResultCode.ERROR, "");
		}
	}
}
